const express = require("express")

const { setToken } =require('../token/constant')
var {
  setCrypto
} = require('../tool/crypto.js')

// const JwtUtil=require("../mod/jwt")
const {
  createToken
} = require("../tool/jwt.js")

const User= require('../mod/user')


const login = express.Router() //创建路由

// login.post("/register", () => {

// })


login.post("/", async (req, res) => { //必须要先匹配到/login ，才能来这儿

  let {password}=req.body
  password = setCrypto(password)
  req.body.password=password
  
  let newuser = await User.findOne({
    email: req.body.email
  })

  if (!newuser) {
    return res.status(202).send({
      code: 202,
      message: "用户不存在"
    })
  } else {
    if (newuser.password !== req.body.password) {
      return res.status(203).send({
        code: 203,
        message: "密码错误"
      })
    } else {
      if (req.body.yzm.toLowerCase() == process.env.captcha) {
        //设置token
      let token=setToken(req.query.name)

        res.status(200).send({
          message: "登录成功",
          token: token,
          user:newuser,
          code:200
        })
      } else {
        res.status(200).send({
          code: 204,
          message: '验证码错误'
        })
      }
    }
  }

})


module.exports = login